<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="top-bar">
      <text class="top-title">任务大厅</text>
    </view>

    <!-- 列表标题和筛选按钮 -->
    <view class="list-header">
      <text class="list-title">工单列表</text>
      <view class="filter-toggle" @click="toggleFilter">
        <text v-if="!showFilter">筛选</text>
        <text v-else>收起</text>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar" v-if="showFilter">
      <view 
        class="filter-item" 
        :class="{ active: currentFilter === '全部' }" 
        @click="changeFilter('全部')"
      >全部</view>
      <view 
        class="filter-item" 
        :class="{ active: currentFilter === '可抢工单' }" 
        @click="changeFilter('可抢工单')"
      >可抢工单</view>
      <view 
        class="filter-item" 
        :class="{ active: currentFilter === '处理中' }" 
        @click="changeFilter('处理中')"
      >处理中</view>
      <view 
        class="filter-item" 
        :class="{ active: currentFilter === '已完成' }" 
        @click="changeFilter('已完成')"
      >已完成</view>
      <view 
        class="filter-item" 
        :class="{ active: currentFilter === '已结算' }" 
        @click="changeFilter('已结算')"
      >已结算</view>
    </view>

    <!-- 工单列表区域 -->
    <view class="workorder-list">
      <view class="loading-state" v-if="isRequesting">
        <text class="loading-text">加载工单中...</text>
      </view>

      <!-- 工单列表 -->
      <view 
        class="workorder-item" 
        v-for="(item, index) in filteredWorkorders" 
        :key="item.id" 
        @click="goDetail(item)"
        v-else
      >
        <view class="item-top">
          <view class="item-title">{{ item.title }}</view>
          <view class="item-status" :class="item.statusClass">{{ item.status }}</view>
        </view>
        <view class="item-info">
          <view class="info-row">工单编号：{{ item.orderNo }}</view>
          <view class="info-row">创建时间：{{ item.createTime }}</view>
          <view class="info-row">地点：{{ item.location }}</view>
          <view class="info-row">提交人：{{ item.submitter }}</view>
          <view class="info-row urgency-row" :class="item.urgencyClass">
            紧急程度：{{ item.urgency }}
            <text class="raw-value" v-if="item.urgency === '未知'">（原始值: {{ item.rawPriority }}）</text>
          </view>
          <view class="info-row" v-if="item.handler">处理人：{{ item.handler }}</view>
        </view>

        <!-- 抢单按钮或已拒绝标签 -->
        <view class="grab-btn-container" v-if="item.status === '可抢工单'">
          <button 
            class="grab-btn" 
            @click.stop="grabOrder(item, index)" 
            :disabled="item.isGrabbing"
            v-if="!rejectedOrderIds.includes(item.id)"
          >
            {{ item.isGrabbing ? '抢单中...' : '抢单' }}
          </button>
          <view class="rejected-tag" v-else>已拒绝</view>
        </view>
      </view>

      <view class="empty-state" v-if="!isRequesting && filteredWorkorders.length === 0">
        <text class="empty-icon">📭</text>
        <text>暂无{{ currentFilter === '可抢工单' ? '可抢工单' : '相关工单' }}</text>
      </view>
    </view>

    <!-- 底部导航组件 -->
    <view class="bottom-nav-container">
      <bottom-nav :currentPath="currentPagePath"></bottom-nav>
    </view>
  </view>
</template>

<script>
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';

export default {
  components: { bottomNav },
  data() {
    return {
      showFilter: false,
      currentFilter: '全部',
      workorderData: [],
      allWorkorderData: [],
      currentPagePath: '/pages/Employee/index/index',
      isRequesting: false,
      refreshTimer: null,
      employeeId: null,
      employeeName: null,
      rejectedOrderIds: [], 
      statusMap: { 0: '可抢工单', 1: '处理中', 2: '已完成', 3: '已结算' },
      urgencyMap: { 1: '普通', 2: '紧急' },
      filterToStatus: { '全部': null, '可抢工单': 0, '处理中': 1, '已完成': 2, '已结算': 3 }
    };
  },
  onLoad() {
    this.getEmployeeInfo();
    // 定时刷新
    this.refreshTimer = setInterval(() => {
      this.getRejectedOrderIds();
      this.getWorkorderList();
    }, 30000);
  },
  onUnload() {
    clearInterval(this.refreshTimer);
  },
  computed: {
    filteredWorkorders() {
      if (this.currentFilter === '全部') {
        return this.workorderData;
      }
      return this.workorderData.filter(item => item.status === this.currentFilter);
    }
  },
  methods: {
    // 获取员工信息
    getEmployeeInfo() {
      const userId = uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }

      uni.request({
        url: `http://localhost:6013/order-client/api/employeeInfo/getByUserId?userId=${userId}`,
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (res) => {
          if (res.data?.code === 0 && res.data.data?.id) {
            this.employeeId = res.data.data.id;
            this.employeeName = res.data.data.name || '未知员工';
            this.getRejectedOrderIds().then(() => {
              this.getWorkorderList();
            });
          } else {
            uni.showToast({ title: '获取接单员信息失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络错误，无法获取身份', icon: 'none' });
        }
      });
    },

    // 获取当前员工拒绝过的工单ID列表
    getRejectedOrderIds() {
      return new Promise((resolve) => {
        if (!this.employeeId) {
          resolve();
          return;
        }

        const params = {
          pageNo: 1,
          pageSize: 9999,
          employeeId: this.employeeId
        };

        uni.request({
          url: 'http://localhost:6013/order-client/api/workOrderInfo/getMyRejectedOrder',
          method: 'POST',
          header: { 'Content-Type': 'application/json' },
          data: params,
          success: (res) => {
            if (res.data?.code === 0 && res.data.data?.records) {
              this.rejectedOrderIds = res.data.data.records.map(item => item.id);
              console.log('当前员工拒绝的工单ID:', this.rejectedOrderIds);
            } else {
              this.rejectedOrderIds = [];
            }
          },
          fail: (err) => {
            console.error('获取拒绝工单列表失败:', err);
            this.rejectedOrderIds = [];
          },
          complete: () => {
            resolve();
          }
        });
      });
    },

    changeFilter(filter) {
      this.currentFilter = filter;
      this.showFilter = false;
      this.getRejectedOrderIds().then(() => {
        this.getWorkorderList();
      });
    },

    // 加载工单列表
    getWorkorderList() {
      this.isRequesting = true;
      const status = this.filterToStatus[this.currentFilter];
      const params = { pageNum: 1, pageSize: 9999 };
      if (status !== null) {
        params.status = status;
      }

      uni.request({
        url: 'http://localhost:6013/order-client/api/workOrderInfo/queryPageList',
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        data: params,
        success: (res) => {
          this.isRequesting = false;
          if (res.data?.code === 0) {
            const responseData = res.data.data || {};
            this.allWorkorderData = responseData.records || [];
            this.totalCount = Number(responseData.total) || this.allWorkorderData.length;

            this.workorderData = this.allWorkorderData.map(item => {
              const rawPriority = Number(item.priorityType);
              const urgency = this.urgencyMap[rawPriority] || '未知';
              return {
                ...item,
                status: this.statusMap[item.status] || '未知状态',
                statusClass: this.getStatusClass(this.statusMap[item.status]),
                urgency: urgency,
                rawPriority: item.priorityType,
                urgencyClass: this.getUrgencyClass(urgency),
                orderNo: item.orderNo || item.id,
                title: item.title || '无标题',
                createTime: this.formatTime(item.createTime) || '未知时间',
                location: item.address || '未填写',
                submitter: item.submitter || item.name || '未知',
                handler: item.employeeId ? (item.employeeName || '已分配') : '',
                isGrabbing: false
              };
            });
          } else {
            this.totalCount = 0;
            this.allWorkorderData = [];
            this.workorderData = [];
          }
        },
        fail: (err) => {
          this.isRequesting = false;
          console.error('工单接口请求失败:', err);
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    },

    getStatusClass(statusText) {
      switch (statusText) {
        case '可抢工单': return 'status-pending';
        case '处理中': return 'status-processing';
        case '已完成': return 'status-completed';
        case '已结算': return 'status-settled';
        default: return '';
      }
    },

    getUrgencyClass(urgencyText) {
      switch (urgencyText) {
        case '普通': return 'urgency-ordinary';
        case '紧急': return 'urgency-urgent';
        default: return 'urgency-unknown';
      }
    },

    formatTime(isoTime) {
      if (!isoTime) return '';
      try {
        let cleanTime = isoTime.replace(/\.\d{3,}(Z|[+-]\d{2}:?\d{2})?$/, '');
        cleanTime = cleanTime.replace('T', ' ');
        cleanTime = cleanTime.replace(/-/g, '/');
        const date = new Date(cleanTime);
        return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      } catch (e) {
        console.warn(`时间解析失败: ${isoTime}`, e);
        let fallback = isoTime.substring(0, 19).replace('T', ' ').replace(/-/g, '/');
        return fallback || '未知时间';
      }
    },

    toggleFilter() { this.showFilter = !this.showFilter; },
    goDetail(item) { uni.navigateTo({ url: `/pages/Employee/workorder/detail?id=${item.id}` }); },
    grabOrder(item, index) {
      if (!this.employeeId) {
        uni.showToast({ title: '身份无效', icon: 'none' });
        return;
      }
      
      this.$set(this.workorderData[index], 'isGrabbing', true);
      uni.request({
        url: 'http://localhost:6013/order-client/api/employeeInfo/grabOrder',
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: { orderId: item.id, employeeId: this.employeeId },
        success: (res) => {
          this.$set(this.workorderData[index], 'isGrabbing', false);
          if (res.data?.code === 0) {
            uni.showToast({ title: '抢单成功', icon: 'success' });
            // 刷新数据后跳转到工单管理页面
            setTimeout(() => {
              this.getRejectedOrderIds();
              this.getWorkorderList();
              // 使用navigateTo跳转到非tabbar的工单管理页面
              uni.navigateTo({
                url: '/pages/Employee/workorder/workorder'
              });
            }, 1500);
          } else {
            uni.showToast({ title: res.data?.msg || '抢单失败', icon: 'none' });
          }
        },
        fail: () => {
          this.$set(this.workorderData[index], 'isGrabbing', false);
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx; /* 预留底部导航高度，避免内容被遮挡 */
  display: flex;
  flex-direction: column;
}

/* 底部导航容器 - 关键修改：固定在底部始终显示 */
.bottom-nav-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999; /* 确保在其他内容之上 */
  background-color: #fff; /* 添加背景色避免透明问题 */
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1); /* 添加顶部阴影增强视觉效果 */
}

.top-bar {
  background-color: #5555ff;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.top-title { font-size: 36rpx; color: #fff; font-weight: bold; }

.list-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.filter-bar {
  display: flex;
  padding: 16rpx 24rpx;
  border-bottom: 1rpx solid #eee;
  overflow-x: auto;
  background-color: #fff;
}
.filter-item {
  padding: 12rpx 24rpx;
  margin-right: 16rpx;
  border-radius: 24rpx;
  font-size: 28rpx;
  background-color: #f0f0f0;
}
.filter-item.active { background-color: #5555ff; color: #fff; }

.workorder-list {
  padding: 16rpx;
  overflow-y: auto;
  flex: 1;
}
.workorder-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.item-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}
.item-title {
  font-size: 32rpx;
  font-weight: bold;
  flex: 1;
  margin-right: 16rpx;
}
.item-status {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
}

.status-pending { background-color: #e1f5fe; color: #0288d1; }
.status-processing { background-color: #bbdefb; color: #0d47a1; }
.status-completed { background-color: #c8e6c9; color: #388e3c; }
.status-settled { background-color: #a5d6a7; color: #2e7d32; }

.item-info {
  border-top: 1rpx dashed #eee;
  padding-top: 16rpx;
}
.info-row {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
}
.info-row::before {
  content: "•";
  color: #5555ff;
  margin-right: 8rpx;
}

.urgency-ordinary { color: #666; }
.urgency-urgent { color: #e53935; font-weight: bold; }
.urgency-unknown { color: #ff9800; }
.raw-value { font-size: 20rpx; margin-left: 10rpx; }

.grab-btn-container {
  position: absolute;
  bottom: 24rpx;
  right: 24rpx;
}
.grab-btn {
  background-color: #5555ff;
  color: #fff;
  border-radius: 6rpx;
  padding: 8rpx 24rpx;
  font-size: 26rpx;
  border: none;
}

.rejected-tag {
  background-color: #eee;
  color: #999;
  border-radius: 6rpx;
  padding: 8rpx 24rpx;
  font-size: 26rpx;
  text-align: center;
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: 40rpx;
  color: #999;
}
.loading-text { font-size: 28rpx; }

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
}
.empty-icon { font-size: 80rpx; margin-bottom: 24rpx; }
</style>
    